【最常用】两种java中的占位符的使用

您所在的位置:网站首页 java string占位 【最常用】两种java中的占位符的使用

【最常用】两种java中的占位符的使用

2023-12-02 14:06| 来源: 网络整理| 查看: 265

先介绍一下format是什么:

Java中允许我们对指定的对象进行某种格式化,从而得到我们想要的格式化样式。而format可以帮助我们从某种格式转化到我们想要的格式的一种工具。

第一种:使用%s占位,使用String.format转换 public class Test { public static void main(String[] args) { String url = "我叫%s,今年%s岁。"; String name = "小明"; String age = "28"; url = String.format(url,name,age); System.out.println(url); } }

控制台输出: 我叫小明,年28岁。

第二种:使用{1}占位,使用MessageFormat.format转换 public class Test { public static void main(String[] args) { String url02 = "我叫{0},今年{1}岁。"; String name = "小明"; String age = "28"; url02 = MessageFormat.format(url02,name,age); System.out.println(url02); } }

控制台同样输出: 我叫小明,今年28岁。

发现了一个很精华的博客,关于format的详细解析见这里:https://www.jianshu.com/p/c8f16cab35e1#



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3